import { useEffect } from "react";
import { useDispatch } from "react-redux";
import { Outlet, useLocation, useNavigate } from "react-router-dom";
import { Form, Input, Tabs, Dialog } from "antd-mobile";
import { BottomBtn } from "@components";
import { createAction } from "@common/utils";
import { POP_PAGE_STACK } from "@store/global-state/action-types";
import { SAGA_STOCKTAKING_OPS_FINISH } from "@store/stocktaking/saga-types";

const BlindOps = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);
  const [form] = Form.useForm();

  useEffect(() => {
    form.setFields([
      { name: "locationCode", value: searchParams.get("locationCode") },
    ]);
  }, []);

  const handleTabChange = (tabKey) => {
    let currentUrl = location.pathname + location.search;
    if (tabKey === "itemInfo") {
      navigate(currentUrl.replaceAll("barcode-info", "item-info"));
    } else {
      navigate(currentUrl.replaceAll("item-info", "barcode-info"));
    }
  };

  const handleFinish = () => {
    Dialog.confirm({
      content: "确定完成当前库位盘点?",
      onConfirm: () =>
        dispatch(
          createAction(SAGA_STOCKTAKING_OPS_FINISH, {
            orderId: searchParams.get("id"),
            locationId: searchParams.get("locationId"),
            callback: () => {
              dispatch(createAction(POP_PAGE_STACK, navigate));
            },
          })
        ),
    });
  };

  return (
    <>
      <div style={{ marginTop: "45px", marginBottom: "65px" }}>
        <Form form={form} mode="card">
          <Form.Header>基本信息</Form.Header>
          <Form.Item name="locationCode" label="库位">
            <Input readOnly />
          </Form.Item>
        </Form>
        <Tabs
          style={{ backgroundColor: "white" }}
          defaultActiveKey="itemInfo"
          onChange={handleTabChange}
        >
          <Tabs.Tab title="物料信息" key="itemInfo" />
          <Tabs.Tab title="条码信息" key="barcodeInfo" />
        </Tabs>
        <Outlet />
      </div>
      <BottomBtn
        items={[
          {
            btnTxt: "完成",
            color: "primary",
            disabled: searchParams.get("status") === "DONE",
            handler: handleFinish,
          },
        ]}
      />
    </>
  );
};

export default BlindOps;
